package cn.edu.xidian.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import cn.edu.xidian.R;
import cn.edu.xidian.controller.JsonController;
import cn.edu.xidian.controller.ListViewController;
import cn.edu.xidian.dao.Impl.UserDaoImpl;
import cn.edu.xidian.domain.User;
import cn.edu.xidian.untils.IntentCodeUntils;
import cn.edu.xidian.untils.PermissionUntils;
import cn.edu.xidian.untils.SQLiteUntils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.edu.xidian.untils.PermissionUntils.PERMISSION_REQUEST;
import static cn.edu.xidian.untils.UserListViewAdapter.*;

public class MainActivity extends AppCompatActivity {

    private UserDaoImpl userDaoImpl;
    private ListViewController lvControl;
    private ArrayList<User> users = new ArrayList<User>();

    /**
     * 显示界面的方式
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        new PermissionUntils().checkPermission(MainActivity.this, MainActivity.this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //通过工具类创建数据库操作类和sqlite数据库工具类
        SQLiteUntils.getSqliteDB(MainActivity.this);

        //操作user模型的dao层实体类
        userDaoImpl = new UserDaoImpl();

        //第一次获取userlist需要从数据库中获取
        users = userDaoImpl.getUserList(SQLiteUntils.getSqliteDB());

        lvControl = new ListViewController(this.<ListView>findViewById(R.id.mainListView));
        //显示listview组件
        lvControl.showListView(MainActivity.this, users);
    }

    /**
     * 给listview的每个按钮设置一个监听
     *
     * @param v
     */
    public void listViewButtonClick(View v) {

        //设置详细页面的intent
        Intent intent = new Intent(MainActivity.this, DisplayDetailActivity.class);
        //给bundle输入数据
        Bundle bundle = new Bundle();
        String transitionName = v.getTransitionName();//独一无二的标识
        Gson gson = new Gson();
        User user = gson.fromJson(transitionName, User.class);

        bundle.putParcelable("olduser", user);
        //将Bundle绑定到intent
        intent.putExtras(bundle);
        startActivityForResult(intent, IntentCodeUntils.REQUEST_DETAIL);
    }

    /**
     * 将操作选项显示在action bar上
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu, menu);

        SearchView sv = (SearchView) menu.findItem(R.id.search).getActionView();
        //设置监听
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                ArrayList<User> userSearch = new ArrayList<>();
                Pattern pattern = Pattern.compile("(.*)" + query + "(.*)", Pattern.CASE_INSENSITIVE);
                Matcher matcher;
                boolean isMatch;
//                query = "(.*)(?i)" + query + "(.*)";
                for (User user : users) {
                    matcher = pattern.matcher(user.getUser_website());
                    isMatch = matcher.matches();
//                    boolean isMatch = Pattern.matches(query, );
                    if (isMatch) {
                        userSearch.add(user);
                    }
                }
                lvControl.showListView(MainActivity.this, userSearch);

                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                if ("".equals(newText)) {
                    lvControl.showListView(MainActivity.this, users);
                }

                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 对菜单进行单击监听
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        JsonController jsonController = new JsonController();

        switch (item.getItemId()) {
            case R.id.add:
                //启动actvity进行添加信息，并返回一个添加好的信息，在这里将新信息添加到数据库并在主界面添加按钮
                Intent intent = new Intent(this, AddActivity.class);
                startActivityForResult(intent, IntentCodeUntils.REQUEST_ADD);
                break;

            //导出
            case R.id.export:
                jsonController.exportToPhone();
                break;

            //导入
            case R.id.importjson:
                jsonController.importFromPhone();
                users.addAll(jsonController.getUserList());
                Log.i("numbers of import", users.size() + "");
                //导入操作后需要更新userlist
                lvControl.showListView(MainActivity.this, users);

                break;

            case R.id.deleteAll:
                users.clear();
                lvControl.showListView(MainActivity.this, users);
                userDaoImpl.deleteFromdatabase("all");
                break;

        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * 根据返回码执行对应的方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (IntentCodeUntils.REQUEST_ADD == requestCode && resultCode == IntentCodeUntils.RESULT_ADD) {
            Bundle bundle = data.getExtras();

            ArrayList<User> resultUsers = bundle.getParcelableArrayList("newUsersList");
            users.addAll(resultUsers);

            lvControl.updateListView();

            //添加后进行持久化
            int insertNums = userDaoImpl.insertToDatabase(resultUsers.size(), users);
            Log.i("numbers of insert", insertNums + "");

        } else if (IntentCodeUntils.REQUEST_DETAIL == requestCode && resultCode == IntentCodeUntils.RESULT_DETAIL) {
            Bundle bundle = data.getExtras();

            User olduser = bundle.getParcelable("olduser");
            User newuser = bundle.getParcelable("newuser");
            int position = bundle.getInt("position");

            if (newuser == null || newuser.equals(olduser)) {
                //无操作
            } else if ("delete".equals(newuser.getUser_name()) && "delete".equals(newuser.getUser_pwd()) && "delete".equals(newuser.getUser_website())) {
                //删除操作
                users.remove(position);
                lvControl.updateListView();

                //删除该行
                userDaoImpl.deleteFromdatabase(newuser.getUser_id());

            } else if (!newuser.equals(olduser)) {
                //更新操作
                users.set(position, newuser);

                lvControl.updateListView();

                //更新该行
                userDaoImpl.updateToDatabase(newuser);

            }

        }
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }
}
